package com.block.source.service.receive;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.enums.InfoTypeEnum;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.db.entity.*;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.api.ChuanBeiFenQiParam;
import com.block.source.model.api.XiaoMeiYiRongParam;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.ISourceReceiveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class ChuanBeiFenQiReceiveService extends ISourceReceiveService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息为空"));
            return sourceApiResult;
        }

        String data = jsonObjectParamContent.getString("content");
        String paramContentData = SecureUtil.aes(apiSecret.getBytes()).decryptStr(data);
        JSONObject jsonObject = JSONObject.parseObject(paramContentData);
        //过滤
        if (StrUtil.isEmpty(jsonObject.getString("phone_md5")) ||
                jsonObject.getInteger("age") == null ||
                jsonObject.getInteger("gender") == null ||
                jsonObject.getInteger("address_code") == null ||
                jsonObject.getInteger("money") == null ||
                jsonObject.getInteger("sesame") == null ||
                jsonObject.getInteger("room") == null ||
                jsonObject.getInteger("car") == null ||
                jsonObject.getInteger("gjj") == null ||
                jsonObject.getInteger("social") == null ||
                jsonObject.getInteger("policy") == null ||
                jsonObject.getInteger("credit_card") == null ||
                jsonObject.getInteger("huabei") == null ||
                jsonObject.getInteger("baitiao") == null){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息有空值"));
            return sourceApiResult;
        }

        UserDataParam userDataParam = this.getUserDataParam(paramContentData);

        // 获取城市信息
        AddressInfo addressInfo = addressInfoService.getAddressInfoByCityCode(userDataParam.getCityCode());
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getError("城市信息为空"));
            return sourceApiResult;
        }

        // 设置省市信息
        userDataParam.setCityCode(addressInfo.getCityCode());
        userDataParam.setCity(addressInfo.getCity());
        userDataParam.setProvinceCode(addressInfo.getProvinceCode());
        userDataParam.setProvince(addressInfo.getProvince());
        userDataParam.setRealName("默认");

        Integer randomInt = RandomUtil.randomInt(Integer.MAX_VALUE);
        userDataParam.setOutOrderNo(String.valueOf(randomInt));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("进件传入的信息为空"));
            return sourceApiResult;
        }
        String data = jsonObjectParamContent.getString("content");
        String paramContentData = SecureUtil.aes(apiSecret.getBytes()).decryptStr(data);

        ChuanBeiFenQiParam chuanBeiFenQiParam = JSON.parseObject(paramContentData, ChuanBeiFenQiParam.class);

        UserDataParam userDataParam = this.getUserDataParam(paramContentData);

        userDataParam.setMobile(chuanBeiFenQiParam.getPhone());
        userDataParam.setRealName(chuanBeiFenQiParam.getName());

        String requestId = chuanBeiFenQiParam.getProduct_info().getString("order_num");
        SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectByChannelCodeAndOutOrderNo(sourceBaseInfo.getChannelCode(), requestId);
        userDataParam.setOrderNo(String.valueOf(pushResultInfo.getId()));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {


        SourceApiResult sourceApiResult = new SourceApiResult();

        MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
        SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();
        MerchantThirdBaseInfo thirdBaseInfo = sourceApiParam.getThirdBaseInfo();
        List<MerchantThirdProtocolInfo> thirdProtocolInfoList = sourceApiParam.getThirdProtocolInfoList();

        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 200);
        returnObject.put("msg", "操作成功！");
        JSONObject dataObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        dataObject.put("order_num", pushResultInfo.getOutOrderNo());

        // 推送原价(分润渠道返回，固价渠道不返回)
        BigDecimal priceAmount = BigDecimal.ZERO;
        //上游是分润，返回分润后价格
        if (ObjectUtil.equals(ProfitSharingEnum.PROFITPRICE.getValue(),sourceBaseInfo.getPriceType())){
            priceAmount = pushResultInfo.getPriceAmount().multiply(sourceBaseInfo.getTypeRate());//分润后价格
        }
        dataObject.put("price", priceAmount);

        if (StrUtil.equals(merchantBaseInfo.getInfoType(), InfoTypeEnum.APIS.getValue())){
            // 下游是 非 apis 类型
            dataObject.put("company_name", thirdBaseInfo.getCompanyName());
            String companyLogo = thirdBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo_url", "");
            }else {
                dataObject.put("logo_url", companyLogo);
            }
            dataObject.put("product_id", thirdBaseInfo.getProductId());
            dataObject.put("product_name", thirdBaseInfo.getProductName());

            //协议地址
            for (MerchantThirdProtocolInfo protocolInfo : thirdProtocolInfoList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("protocolName",protocolInfo.getProtocolName());
                jsonObject.put("protocolUrl", protocolInfo.getProtocolUrl());
                jsonArray.add(jsonObject);
            }
        }else {
            dataObject.put("company_name", merchantBaseInfo.getCompanyName());
            String companyLogo = merchantBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo_url", "");
            }else {
                dataObject.put("logo_url", merchantBaseInfo.getCompanyLogo());
            }
            dataObject.put("product_id", String.valueOf(merchantBaseInfo.getId()));
            dataObject.put("product_name", merchantBaseInfo.getInfoName());

            //协议地址

            JSONObject jsonObject = new JSONObject();
            ChannelBaseInfo baseInfoByCode = channelCommonService.getBaseInfoByCode(sourceBaseInfo.getChannelCode());
            ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(baseInfoByCode.getAppCode());
            String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), pushResultInfo.getOrderNo(), pushResultInfo.getOrderItemNo());
            jsonObject.put("protocolName","授权协议");
            jsonObject.put("protocolUrl", protocolUrl);
            jsonArray.add(jsonObject);
        }

        dataObject.put("agreement_list", jsonArray);
        String s = SecureUtil.aes(sourceBaseInfo.getApiSecret().getBytes()).encryptBase64(JSONObject.toJSONString(dataObject));

        returnObject.put("return_data", s);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO,SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();

        JSONObject returnObject = new JSONObject();

        JSONObject data = resultInfoVO.getData();
        String respCode = resultInfoVO.getRespCode();

        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()){
            String status = data.getString("status");
            if (StrUtil.equals(status, "000")){
                returnObject = this.getSuccess();
                sourceApiResult.setReturnObject(returnObject);
                return sourceApiResult;
            }
        }

        returnObject = this.getError("推送失败");
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 500);
        returnObject.put("msg", message);
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 200);
        returnObject.put("msg", "推送成功");
        return returnObject;
    }

    @Override
    public UserDataParam getUserDataParam(String paramContent) {

        ChuanBeiFenQiParam chuanBeiFenQiParam = JSON.parseObject(paramContent, ChuanBeiFenQiParam.class);

        UserDataParam userDataParam = new UserDataParam();

        userDataParam.setMobileMd5(chuanBeiFenQiParam.getPhone_md5());
        userDataParam.setMobile(chuanBeiFenQiParam.getPhone());
        userDataParam.setRealName(chuanBeiFenQiParam.getName());

        if (chuanBeiFenQiParam.getGender() == 1){
            userDataParam.setSex("2");
        }else {
            userDataParam.setSex("1");
        }

        userDataParam.setAge(chuanBeiFenQiParam.getAge());

        userDataParam.setCityCode(String.valueOf(chuanBeiFenQiParam.getAddress_code()));

        Integer creditCard = chuanBeiFenQiParam.getCredit_card();
        if (creditCard == 1 || creditCard == 2){
            userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        }else {
            userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk002.getValue());
        }

        userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt007.getValue());

        Integer education = chuanBeiFenQiParam.getEducation();
        if (education != null){
            if (education == 0 || education == 3 || education == 4 || education == 5){
                userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl002.getValue());
            }else if (education == 2){
                userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl003.getValue());
            }else {
                userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl004.getValue());
            }
        }else {
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl001.getValue());
        }

        Integer income = chuanBeiFenQiParam.getIncome();
        if (income == null){
            userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr001.getValue());
        }else if (income < 5000){
            userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr001.getValue());
        }else if (income >= 5000 && income < 10000){
            userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr002.getValue());
        }else {
            userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr004.getValue());
        }

        userDataParam.setWeili(BaseTypeInfoEnum.WeiLi.wl001.getValue());

        Integer baitiao = chuanBeiFenQiParam.getBaitiao();
        if (baitiao == 1){
            userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt001.getValue());
        }else {
            userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt002.getValue());
        }

        Integer huabei = chuanBeiFenQiParam.getHuabei();
        if (huabei == 1){
            userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());
        }else {
            userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb002.getValue());
        }

        userDataParam.setUserIp("127.0.0.1");

        Integer loanAmount = chuanBeiFenQiParam.getMoney();
        if (loanAmount == null){
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
        }else {
            if (loanAmount <= 30000) {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
            } else if (loanAmount > 30000 && loanAmount <= 50000) {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la002.getValue());
            } else if (loanAmount > 50000 && loanAmount <= 100000) {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la003.getValue());
            } else if (loanAmount >100000 && loanAmount <= 200000) {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la004.getValue());
            } else {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la005.getValue());
            }
        }

        Integer houseProperty = chuanBeiFenQiParam.getRoom();
        if (houseProperty == 1){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu001.getValue());
        }else {
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu003.getValue());
        }

        Integer commercialInsurance = chuanBeiFenQiParam.getPolicy();
        if (commercialInsurance == 1){
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx001.getValue());
        }else {
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx003.getValue());
        }

        Integer creditCardLimit = chuanBeiFenQiParam.getCredit();
        if (creditCardLimit == 0 || creditCardLimit == 1 || creditCardLimit == 2 || creditCardLimit == 3){
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq001.getValue());
        }else if (creditCard == 4){
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq002.getValue());
        }else {
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq003.getValue());
        }

        Integer hasFund = chuanBeiFenQiParam.getGjj();
        if (hasFund == 1){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj001.getValue());
        }else if (hasFund == 2){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj002.getValue());
        }else {
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj003.getValue());
        }

        Integer zhimaCredit = chuanBeiFenQiParam.getSesame();
        if (zhimaCredit == 6){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm005.getValue());
        }else if (zhimaCredit == 5){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm004.getValue());
        }else if (zhimaCredit == 4){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm003.getValue());
        }else if (zhimaCredit == 2 || zhimaCredit == 3){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm002.getValue());
        }else {
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm001.getValue());
        }

        Integer hasSocial = chuanBeiFenQiParam.getSocial();
        if (hasSocial == 1){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb001.getValue());
        }else if (hasSocial == 2){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb002.getValue());
        }else {
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb003.getValue());
        }

        Integer carProperty = chuanBeiFenQiParam.getCar();
        if (carProperty == 1){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car001.getValue());
        }else {
            userDataParam.setCar(BaseTypeInfoEnum.Car.car002.getValue());
        }

        Integer professional = chuanBeiFenQiParam.getVocation();
        if (professional == null){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
        }else if (professional == 0 || professional == 1){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
        }else if (professional == 3){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz002.getValue());
        }else if (professional == 5){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz003.getValue());
        }else if (professional == 2){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz004.getValue());
        }else{
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz005.getValue());
        }

        Integer loanTerm = chuanBeiFenQiParam.getPeriods();
        if (loanTerm == null){
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt001.getValue());
        } else if (loanTerm == 24 || loanTerm == 36){
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt004.getValue());
        }else if (loanTerm == 6 || loanTerm == 12){
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt003.getValue());
        }else {
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt001.getValue());
        }


        return userDataParam;
    }

}
